import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import { STColumn, STComponent } from '@delon/abc/st';
import { DatePipe, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { fromEvent, Subscription } from 'rxjs';
import { UsermanageService } from '../../../../services/usercenter.service';

@Component({
  selector: 'app-supplier-components-list-view',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less'],
  providers: [DatePipe]
})
export class FreightComponentsListDetailComponent implements OnInit, OnDestroy {
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('st1') private readonly st1!: STComponent;
  @ViewChild('approvedModal', { static: false })
  approvedModal!: any;
  @ViewChild('redectModal', { static: false })
  redectModal!: any;
  columns: STColumn[] = [];
  recordColumns!: STColumn[];
  detailData: any = { adminUserInfo: { name: '' }, legalPersonIdentityVO: { name: '' } };
  tempalateData = { ...this.detailData };
  suppliersData: any = {};

  isEdit = false;

  uploadURl = apiConf.waterFileUpload;
  disabledUpload = false;
  enterpriseAddressCode: any = [];
  ltdId: any = [];
  roles: any = [];
  customerServices: any = [];
  billEvaluateList: any = [];
  approvalOpinion = '';
  networkTransporter = null;
  roleId = null;
  customerServiceId = null;
  partnerInfo: any = {};
  esignCheckStatus: any = {
    0: '不通过',
    1: '通过',
    2: '未认证'
  };

  billEvaluate = null;
  scrollTop = 0;
  subscribeScoll!: Subscription;
  /**
 * 查询参数
 */
  get reqParamsCar() {
    const params = {
      id: this.route.snapshot.params.id,
      bindType: 0
    }
    return { ...params };
  }
  get reqParams() {
    const params = {
      id: this.route.snapshot.params.id,
    }
    return { ...params };
  }
  constructor(
    public service: UsermanageService,
    private route: ActivatedRoute,
    private nzModalService: NzModalService,
    private router: Router,
    private datePipe: DatePipe
  ) { }
  ngOnDestroy(): void {
    this.subscribeScoll.unsubscribe();
  }

  ngOnInit() {
    this.route.params.subscribe(({ params }) => {
      this.initData();
      this.loadltdId();
      this.loadRoles();
      this.initST();
      this.initRecordST()
      this.loadCustomerServices();
      this.loadPartnerInfo()
    });
    this.subscribeScoll = fromEvent(window, 'scroll').subscribe(event => {
      this.scrollTop = document.documentElement.scrollTop;
    });
  }
  
  /**
* 初始化数据列表
*/
  initST() {
    this.columns = [
      { title: '修改后合伙人', index: 'newPartnerName', className: 'text-center' },
      { title: '修改前合伙人', index: 'originalPartnerName', className: 'text-center' },
      { title: '结算起算日', index: 'settStartTime', className: 'text-center' },
      { title: '生效节点', index: 'effectiveNode', className: 'text-center', type: 'enum', enum: {
        1: '立即生效',
        2: 'CRM审核后生效',
        3: '审核通过生效',
      } },
      {
        title: 'CRM审核状态', index: 'effectiveStatus',
        type: 'enum',
        enum: {
          0: '已失效',
          1: '未生效',
          2: '已生效',
        },
        className: 'text-center'
      },
      { title: '修改时间', index: 'modifyTime', className: 'text-center' },
      { title: '生效时间', index: 'effectiveTime', className: 'text-center' },
      { title: '操作人', index: 'modifyUserId', className: 'text-center' },
      { title: '备注', render: 'remark', className: 'text-center' },
    ];
  }
  /**
   * 初始化数据列表
   */
  initRecordST() {
    this.recordColumns = [
      { title: '修改后渠道销售', index: 'newChannelName', className: 'text-center' },
      { title: '修改前渠道销售地', index: 'originalChannelName', className: 'text-center' },
      { title: '生效节点', index: 'effectiveNode', className: 'text-center', type: 'enum', enum: {
        1: '立即生效',
        2: 'CRM审核后生效',
        3: '审核通过生效',
      } },
      {
        title: 'CRM审核状态', index: 'effectiveStatus',
        type: 'enum',
        enum: {
          0: '已失效',
          1: '未生效',
          2: '已生效',
        },
        className: 'text-center'
      },
      { title: '修改时间', index: 'modifyTime', className: 'text-center' },
      { title: '生效时间', index: 'effectiveTime', className: 'text-center' },
      { title: '操作人', index: 'modifyUserId', className: 'text-center' },
      { title: '备注', render: 'remark', className: 'text-center' },
    ];
  }
  loadPartnerInfo(){
    this.service.request(this.service.$api_getEnterpriceRel, {id: this.route.snapshot.params.id}).subscribe(res => {
      if (res) {
        this.partnerInfo = res;
      }
    });
  }
  loadltdId() {
    this.service.getNetworkFreightForwarder().subscribe(res => {
      if (res) {
        this.ltdId = res;
      }
    });
  }
  loadRoles() {
    this.service.getRoles({ enterpriseId: 0, projectId: 0 }).subscribe(res => {
      if (res) {
        this.roles = res;
      }
    });
  }
  loadCustomerServices() {
    this.service.getStaffList({}, false).subscribe(res => {
      if (res) {
        this.customerServices = res;
      }
    });
  }

  initData() {
    this.service
      .request(this.service.$api_get_freight_detail, {
        id: this.route.snapshot.params.id
      })
      .subscribe(res => {
        if (res) {
          this.detailData = res;
          this.tempalateData = { ...this.detailData };
          this.enterpriseAddressCode = [
            Number(this.detailData.fullRegionVO?.provinceCode),
            Number(this.detailData.fullRegionVO?.cityCode),
            Number(this.detailData.fullRegionVO?.areaCode)
          ];
        }
      });

    // 获取评价信息
    this.service
      .request(this.service.$api_get_driver_billEvaluate, { passiveUserId: this.route.snapshot.params.id }, 'POST', false)
      .subscribe(res => {
        if (res?.length > 0) {
          this.service.request(this.service.$api_get_freight_billEvaluate, res).subscribe(billEvaluate => {
            if (billEvaluate) {
              this.billEvaluate = billEvaluate.totalScore;
              this.billEvaluateList = res;
            }
          });
        }
      });
  }

  goBack() {
    window.history.go(-1);
  }
  /**
   * 冻结
   */
  freezeOrResume(type: number) {
    this.service.http
      .post(this.service.$api_lock_freight, {
        id: this.route.snapshot.params.id,
        statedLocked: !!type
      })
      .subscribe(res => {
        if (res.data === true) {
          if (type === 0) {
            this.service.msgSrv.success(`启用成功！`);
          } else {
            this.service.msgSrv.success(`冻结成功！`);
          }
          this.initData();
        } else {
          this.service.msgSrv.error(res.msg || '操作失败！');
        }
      });
  }

  /**
   * 支付权限
   */
  PayOrResume(type: number) {
    this.service.http
      .post(this.service.$api_lock_freight, {
        id: this.route.snapshot.params.id,
        statedLocked: !!type
      })
      .subscribe(res => {
        if (res.data === true) {
          if (type === 1) {
            this.service.msgSrv.success(`开启成功！`);
          } else {
            this.service.msgSrv.success(`关闭成功！`);
          }
          this.initData();
        } else {
          this.service.msgSrv.error(res.msg || '操作失败！');
        }
      });
  }

  auditPass(isSave: boolean) {
    this.networkTransporter = null;
    this.roleId = null;
    this.customerServiceId = null;
    this.nzModalService.create({
      nzTitle: '审核通过',
      nzContent: this.approvedModal,
      nzOnOk: () => {
        if (!this.networkTransporter || !this.roleId || !this.customerServiceId) {
          return false;
        }
        if (isSave) {
          this.save({
            passSave: true,
            roleId: this.roleId,
            networkTransporter: this.networkTransporter
          });
        } else {
          this.auditEnterprise(20);
        }
        return;
      }
    });
  }
  auditNo() {
    this.approvalOpinion = '';
    this.roleId = null;
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.redectModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          return false;
        }
        this.auditEnterprise(30);
        return;
      }
    });
  }

  private auditEnterprise(status: number) {
    this.service
      .request(this.service.$api_audit_freight, {
        approvalStatus: status,
        id: this.detailData.id,
        approvalOpinion: this.approvalOpinion,
        networkTransporter: this.networkTransporter,
        customerServiceId: this.customerServiceId,
        roleId: this.roleId || null
      })
      .subscribe(res => {
        if (res) {
          this.service.msgSrv.success(status === 20 ? '审核通过' : '驳回成功');
          this.refreshData(status);
        }
      });
  }

  ratify() {
    this.isEdit = true;
  }

  deleteImg(data: any, key: string, key2: string) {
    this.nzModalService.warning({
      nzTitle: '是否确认删除该图片',
      nzOnOk: () => {
        this.disabledUpload = true;
        data[key] = '';
        data[key2] = '';
        setTimeout(() => {
          this.disabledUpload = false;
        }, 100);
      }
    });
  }
  changeUpload({ file, fileList, type }: any, data: any, key: string, key2: string, id: string) {
    if (type === 'success') {
      data[key] = file.response.data?.fullFileWatermarkPath;
      data[key2] = file.response.data?.fullFilePath;
      if (id === 'legalFront' || id === 'legalBack') {
        this.checkIdCard(file.response.data?.fullFilePath, id === 'legalFront' ? 'front' : 'back', 1);
      }
      if (id === 'certificateBackFront' || id === 'certificateBack') {
        this.checkIdCard(file.response.data?.fullFilePath, id === 'certificateBackFront' ? 'front' : 'back', 0);
      }
      if (id === 'detailPhoto') {
        this.checkBusinessLicense(file.response.data?.fullFilePath);
      }
    }
  }

  /**
   * 级联获取地区数据
   * @param node 节点
   * @param index 层级
   * @returns
   */
  loadRegionData = (node: any, index: number) => {
    return new Promise(resolve => {
      this.service.request(this.service.$api_get_region_by_code, { regionCode: node?.regionCode || '' }).subscribe(
        res => {
          node.children = res.map((item: any) => ({ ...item, isLeaf: index === 1, value: item.regionCode, label: item.name }));
        },
        _ => { },
        () => {
          resolve(node);
        }
      );
    });
  };

  reset() {
    this.detailData = { ...this.tempalateData };
    this.isEdit = false;
  }

  save(data: any) {
    const dateil = { ...this.detailData };
    Object.assign(dateil.legalPersonIdentityVO, {
      validStartTime: this.datePipe.transform(dateil.legalPersonIdentityVO.validStartTime, 'yyyy-MM-dd'),
      validEndTime: this.datePipe.transform(dateil.legalPersonIdentityVO.validEndTime, 'yyyy-MM-dd')
    });
    if (!this.detailData?.enterpriseName || !this.detailData?.enterpriseAddress) {
      this.service.msgSrv.error('请完善企业基本信息！')
      return false;
    }
    if (!this.detailData.legalPersonIdentityVO.name || !this.detailData.legalPersonIdentityVO.certificateNumber) {
      this.service.msgSrv.error('请完善法人信息！')
      return false;
    }
    if (!this.detailData.createBank || !this.detailData.bankAccount) {
      this.service.msgSrv.error('请完善企业开票信息！')
      return false;
    }
    const params = {};
    Object.assign(params, {
      adminMobile: dateil.adminMobile,
      adminAppUserId: dateil.adminAppUserId,
      adminUserInfo: { ...dateil.adminUserInfo },
      bankAccount: dateil.bankAccount,
      businessScope: dateil.businessScope,
      createBank: dateil.createBank,
      creditPhoto: dateil.creditPhoto,
      creditPhotoWatermark: dateil.creditPhotoWatermark,
      enterpriseAddress: dateil.enterpriseAddress,
      enterpriseAddressCode: this.enterpriseAddressCode[2],
      enterpriseLogo: dateil.enterpriseLogo,
      enterpriseName: dateil.enterpriseName,
      enterpriseRegistrationTime: this.datePipe.transform(dateil.enterpriseRegistrationTime, 'yyyy-MM-dd'),
      enterpriseType: dateil.enterpriseType,
      id: dateil.id,
      legalPersonIdentityDTO: { ...dateil.legalPersonIdentityVO },
      licensePhoto: dateil.licensePhoto,
      licensePhotoWatermark: dateil.licensePhotoWatermark,
      networkTransporter: dateil.networkTransporter,
      oftenUsedServices: dateil.oftenUsedServices,
      operatingEndTime: this.datePipe.transform(dateil.operatingEndTime, 'yyyy-MM-dd'),
      operatingStartTime: this.datePipe.transform(dateil.operatingStartTime, 'yyyy-MM-dd'),
      promotersTelephone: dateil.promotersTelephone,
      registerAddress: dateil.registerAddress,
      registerPhone: dateil.registerPhone,
      registrationCapital: dateil.registrationCapital,
      taxAuthority: dateil.taxAuthority,
      unifiedSocialCreditCode: dateil.unifiedSocialCreditCode
    });
    Object.assign(params, { ...data });
    this.service.request(this.service.$api_save_enterprise_admin, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('企业修改成功');
        this.refreshData(data.passSave ? 20 : 10);
        this.isEdit = false;
      }
    });
    return
  }

  private refreshData(status: number) {
    if (status === 20) {
      this.service.request(this.service.$api_get_next_audit_freight, { id: this.route.snapshot.params.id }).subscribe(res => {
        if (res?.id) {
          this.router.navigate(['/usercenter/freight/enterprise/detail/' + res.id]);
        } else {
          this.initData();
        }
      });
    } else {
      this.initData();
    }
  }

  // 识别身份证 参数isFront：front-正面、back-背面；type：0-申请人身份证，1-法定代表人身份证
  checkIdCard(imgurl: any, isFront: string, type: number) {
    const params = {
      idCardUrl: imgurl,
      side: isFront
    };
    this.service.request(this.service.$api_ocr_recognize_id_card, params).subscribe(res => {
      if (res) {
        if (type === 1) {
          // 法定代表人证件照
          if (isFront === 'front') {
            // 正面
            if (res.name) {
              this.detailData.legalPersonIdentityVO.name = res.name;
            }
            if (res.number) {
              this.detailData.legalPersonIdentityVO.certificateNumber = res.number;
            }
          }
          if (isFront === 'back') {
            // 背面
            if (res.validFrom) {
              this.detailData.legalPersonIdentityVO.validStartTime = res.validFrom;
            }
            if (res.validTo) {
              this.detailData.legalPersonIdentityVO.validEndTime = res.validTo;
            } else {
              this.detailData.legalPersonIdentityVO.validEndTime = null;
            }
          }
        }
        // 企业管理员证件照
        if (type === 0) {
          if (isFront === 'front') {
            // 正面
            if (res.name) {
              this.detailData.adminUserInfo.name = res.name;
            }
            if (res.number) {
              this.detailData.adminUserInfo.certificateNumber = res.number;
            }
          }
        }
      }
    });
  }

  // 识别营业执照
  checkBusinessLicense(imgurl: any) {
    this.service.request(this.service.$api_ocr_recognize_business_license, { businessLicenseUrl: imgurl }).subscribe(res => {
      if (res) {
        if (res.registrationNumber) {
          this.detailData.unifiedSocialCreditCode = res.registrationNumber;
        }
        if (res.name) {
          this.detailData.enterpriseName = res.name;
        }
        // if (res.type) {
        //   this.detailData.enterpriseType = res.type;
        // }
        if (res.addressRegionCodes) {
          this.detailData.enterpriseAddressCode = res.addressRegionCodes;
        }
        if (res.address) {
          this.detailData.enterpriseAddress = res.address;
        }
        if (res.registeredCapital) {
          this.detailData.registrationCapital = res.registeredCapital;
        }
        if (res.foundDate) {
          this.detailData.enterpriseRegistrationTime = res.foundDate;
        }
        if (res.businessTermStartDate) {
          this.detailData.operatingStartTime = res.businessTermStartDate;
        }
        if (res.businessTermEndDate) {
          this.detailData.operatingEndTime = res.businessTermEndDate;
        } else {
          this.detailData.operatingEndTime = null;
        }
        if (res.businessScope) {
          this.detailData.businessScope = res.businessScope;
        }
      }
    });
  }
}
